package com.example.smartcity_ikun_new2.ui.home

import android.content.Context
import android.content.Intent
import android.opengl.ETC1.getHeight
import android.os.Bundle
import android.view.Display
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.view.inputmethod.EditorInfo
import android.widget.LinearLayout
import android.widget.TextView
import android.widget.Toast
import androidx.fragment.app.Fragment
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProviders
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.viewpager2.adapter.FragmentStateAdapter
import com.bumptech.glide.Glide
import com.example.smartcity_ikun_new2.AppContext
import com.example.smartcity_ikun_new2.R
import com.example.smartcity_ikun_new2.databinding.FragmentHomeBinding
import com.example.smartcity_ikun_new2.logic.network.SmartCityNetWorkCreate
import com.example.smartcity_ikun_new2.logic.utils.KotlinUtils.show
import com.example.smartcity_ikun_new2.ui.NewsShow.EditTextShowActivity
import com.example.smartcity_ikun_new2.ui.NewsShow.NewsShowActivity
import com.example.smartcity_ikun_new2.ui.home.NewsFragment.*
import com.example.smartcity_ikun_new2.ui.home.adapter.HomeHotRecyclerViewAdapter
import com.example.smartcity_ikun_new2.ui.home.adapter.HomeMoreRecyclerViewAdapter
import com.example.smartcity_ikun_new2.ui.home.model.HomeHotEntity
import com.example.smartcity_ikun_new2.ui.home.model.HomeMoreEntity
import com.google.android.material.tabs.TabLayout
import com.google.android.material.tabs.TabLayoutMediator
import com.youth.banner.adapter.BannerImageAdapter
import com.youth.banner.holder.BannerImageHolder
import com.youth.banner.indicator.CircleIndicator
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch

class HomeFragment : Fragment() {

    private val viewModel by lazy {
        ViewModelProviders.of(this)[HomeViewModel::class.java]
    }



    private lateinit var mBinding: FragmentHomeBinding
    override fun onCreateView(
            inflater: LayoutInflater,
            container: ViewGroup?,
            savedInstanceState: Bundle?
    ): View {
        mBinding = FragmentHomeBinding.inflate(inflater, container, false)

        // 模糊查询
        setEditText()

        // banner
        setBanner()

        // More
        setMore()

        // Hot
        setHot()

        // NewsTitle
        setNewsTitle()

        return mBinding.root
    }




    private fun setEditText() {
        mBinding.homeEditText.setOnEditorActionListener { textView, i, keyEvent ->
            if (i == EditorInfo.IME_ACTION_SEARCH){
                startActivity(Intent(context, EditTextShowActivity::class.java).apply {
                    putExtra("EditText", mBinding.homeEditText.text.toString())
                })
            }
            false
        }
    }

    /**
     *  Banner
     */
    private fun setBanner() {
        val arrayImageUrl = ArrayList<String>()
        viewModel.setGuide(mutableMapOf<String, Int>().apply {
            this["pageNum"] = 1
            this["pageSize"] = 8
            this["type"] = 2
        })
        viewModel.guideLiveData.observe(this, Observer {
            if (it.code == "200") {
                viewModel.guideList.clear()
                viewModel.guideList.addAll(it.rows)
            } else Toast.makeText(context, "加载轮播图出错！", Toast.LENGTH_SHORT).show()

            for (i in viewModel.guideList) arrayImageUrl.add(SmartCityNetWorkCreate.baseUrl + i.advImg)

            // BannerAdapter
            mBinding.homeBanner.apply {
                this.setBannerRound(20F)
                this.addBannerLifecycleObserver(this@HomeFragment).indicator = CircleIndicator(AppContext.context)
                this.adapter = object : BannerImageAdapter<String>(arrayImageUrl){
                    override fun onBindView(p0: BannerImageHolder?, p1: String?, p2: Int, p3: Int) {
                        Glide.with(context)
                            .load(p1)
                            .into(p0?.imageView!!)
                    }
                }

                // 点击事件
                this.setOnBannerListener{ data, position ->
                    this@HomeFragment.startActivity(Intent(context, NewsShowActivity::class.java).apply {
                        putExtra("banner", position.toString())
                    })
                }
                this.start()
            }
        })
    }


    /**
     * More
     */
    private fun setMore() {
        val array = ArrayList<HomeMoreEntity>()

        // 设置RecyclerView适配器
        mBinding.homeRecyclerView.apply {
            this.layoutManager = GridLayoutManager(context, 5)
            this.adapter = HomeMoreRecyclerViewAdapter(this@HomeFragment, array)
        }

        // 获取数据
        viewModel.setMore("N")
        viewModel.moreLiveData.observe(this, Observer {
            if (it.code == 200){
                viewModel.moreList.clear()
                viewModel.moreList.addAll(it.rows)
            }

            for (i in viewModel.moreList){
                if (array.size < 9){
                    array.add(HomeMoreEntity(SmartCityNetWorkCreate.baseUrl + i.imgUrl, i.serviceName))
                    mBinding.homeRecyclerView.adapter?.notifyItemChanged(array.size)
                }
            }

            array.add(HomeMoreEntity("", "全部服务"))
        })
    }


    /**
     * Hot
     */
    private fun setHot(){
        val arrayAdapter = ArrayList<HomeHotEntity>()
        mBinding.homeHotRecyclerView.apply {
            this.layoutManager = LinearLayoutManager(context).apply {
                this.orientation = LinearLayoutManager.HORIZONTAL
            }
            this.adapter = HomeHotRecyclerViewAdapter(arrayAdapter)
        }

        viewModel.setHot("Y")
        viewModel.hotLiveData.observe(this, Observer {
            if (it.code == 200){
                viewModel.hotList.clear()
                viewModel.hotList.addAll(it.rows)
            }

            for (i in viewModel.hotList){
                arrayAdapter.add(HomeHotEntity(SmartCityNetWorkCreate.baseUrl + i.cover, i.title))
                mBinding.homeHotRecyclerView.adapter?.notifyItemInserted(arrayAdapter.size)
            }
        })


    }


    /**
     * NewsTitle
     */
    private fun setNewsTitle(){
        val  str = listOf<String>("今日要闻", "专题聚焦", "政策解读", "经济发展", "文化旅游", "科技创新")
        mBinding.homeViewPager2.adapter = object : FragmentStateAdapter(this){
            override fun getItemCount() = 6
            override fun createFragment(position: Int): Fragment = when(position){
                0 -> NewsFrament()
                1 -> NewsFragment2()
                2 -> NewsFragment3()
                3 -> NewsFragment4()
                4 -> NewsFragment5()
                else -> NewsFragment6()
            }
        }

        mBinding.homeTabLayout.tabMode = TabLayout.MODE_SCROLLABLE
        TabLayoutMediator(mBinding.homeTabLayout, mBinding.homeViewPager2){tab, position ->
            when(position){
                0 -> tab.text = str[0]
                1 -> tab.text = str[1]
                2 -> tab.text = str[2]
                3 -> tab.text = str[3]
                4 -> tab.text = str[4]
                else -> tab.text = str[5]
            }
        }.attach()
    }
}